package etnorservice.etnor_service.controller;

import etnorservice.etnor_service.domain.po.DocumentSpace;
import etnorservice.etnor_service.mapper.WorkspaceTreeMapper;
import etnorservice.etnor_service.request.SpaceCreateRequest;
import etnorservice.etnor_service.result.Result;
import etnorservice.etnor_service.service.DocumentSpaceService;
import etnorservice.etnor_service.service.UserService;
import etnorservice.etnor_service.service.impl.WorkspceService;
import etnorservice.etnor_service.utils.AesUtil;
import etnorservice.etnor_service.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2024/08/30/10:23
 **/
@RestController
public class WorkSpaceContoller {
    @Autowired
    WorkspaceTreeMapper workspaceTreeMapper;
    @Autowired
    WorkspceService workspceService;
    @Autowired
    UserService userService;
    @Autowired
    DocumentSpaceService documentSpaceService;
    @GetMapping("/system/getspaceTree")
    public Result getTree(@RequestHeader
                                      (value = "Authorization", required = false)
                                      String authorizationHeader
                          ){
        Result result=new Result();
        String account=
                new JwtTokenUtil().
                        getAccountFromToken(extractTokenFromHeader(authorizationHeader));
        Integer id=Integer.parseInt(account);
        String user=userService.findRoleByAccount(id).getAccount();
        try {
            result.setData(workspceService.getTree(user));
        }catch (Exception e){
            result.setMessage(e.getMessage());
        }

        return result;
    }

    private String extractTokenFromHeader(String header) {
        if (header == null || !header.startsWith("Bearer ")) {
            return null;
        }
        return header.substring(7).trim(); // 去除 "Bearer ".length() 后面的空格
    }
    //获取所有顶级节点
    @GetMapping("/system/getTopSpace")
    public Result getTop(){
        Result result=new Result();
        result.setData(workspceService.getTopList());

        return result;
    }
    /*
    * 2024-10-19 新需求
    * 获取用户所在的空间
    * @Parm:account String
    *
    * */
    @GetMapping("/system/user/blog/personSpace")
    public Result getUserDocumentSpace(@RequestHeader
                                                   (value = "Authorization", required = false)
                                                   String authorizationHeader
    ) throws Exception {
        Result result=new Result();
        String account=
                new JwtTokenUtil().
                        getAccountFromToken(extractTokenFromHeader(authorizationHeader));
        List<String> spaceIds=documentSpaceService.getSpaceIdByAccount(account);
        List<List<DocumentSpace>> documents=new ArrayList<>();
        for(String spaceId:spaceIds){
            documents.add(documentSpaceService.findDocumentSpaces(spaceId));
        }
         // 使用 HashSet 去重
        Set<DocumentSpace> uniqueDocumentsSet = new HashSet<>();
        for (List<DocumentSpace> docList : documents) {
            uniqueDocumentsSet.addAll(docList);
        }

        // 将 Set 转换回 List
        List<DocumentSpace> uniqueDocuments = new ArrayList<>(uniqueDocumentsSet);
         for(DocumentSpace documentSpace:uniqueDocuments){
            documentSpace.setSpaceId(AesUtil.encrypt(documentSpace.getSpaceId()));
            if(documentSpace.getParentId()!=null){
                documentSpace.setParentId(AesUtil.encrypt(documentSpace.getParentId()));
            }
        }
        result.setData(uniqueDocuments);
        return result;
    }

    @PostMapping("/system/user/blog/space")
    public Result createSpace(
            @RequestParam (required = true) String spaceName,
            @RequestParam (required = true) String parentId,
            @RequestParam (required = true) String visibilityScope,
            @RequestHeader(value = "Authorization", required = false) String authorizationHeader
    ) throws Exception {
        Result result = new Result();
  String account=
                new JwtTokenUtil().
                        getAccountFromToken(extractTokenFromHeader(authorizationHeader));


        Integer id=Integer.parseInt(account);
        SpaceCreateRequest spaceCreateRequest= new SpaceCreateRequest();

        //判断parentId是否存在
        parentId=AesUtil.decrypt(parentId);
        DocumentSpace spaceNameBySpaceId = documentSpaceService.findSpaceNameBySpaceId(parentId);
        if(spaceNameBySpaceId.getSpaceStatus().equals("inactive")){
            result.setCode(400);
            result.setMessage("不允许在已经停用的空间下创建空间!!!");
        }else{
            spaceCreateRequest.setSpaceName(spaceName);
            spaceCreateRequest.setParentId(parentId);
            spaceCreateRequest.setOwnerId(id+"");
            spaceCreateRequest.setVisibilityScope(visibilityScope);
        }
        try {
            documentSpaceService.createDocumentSpace(spaceCreateRequest);
            result.setCode(200);
            result.setMessage("创建成功");
        }catch (Exception e){
            result.setCode(500);
            result.setMessage("系统错误，请联系管理员!");
        }

        return result;
    }

    @PostMapping("/system/user/blog/space/{spaceId}")
    public Result deleteSpace(
            @PathVariable("spaceId") String spaceId,
    @RequestHeader(value = "Authorization", required = false) String authorizationHeader
    ) throws Exception {

  String account=
                new JwtTokenUtil().
                        getAccountFromToken(extractTokenFromHeader(authorizationHeader));


        Integer id=Integer.parseInt(account);
        Result result = new Result();
        String space=AesUtil.decrypt(spaceId);
        DocumentSpace spaceNameBySpaceId =
                documentSpaceService.findSpaceNameBySpaceId(space);
        //如果节点不允许删除
        if(spaceNameBySpaceId.getIsDelete().equals("0")){
            result.setCode(40001);
            result.setMessage("注意，该节点不允许删除");
            return result;
        }
        //如果有子节点，不允许删除
        if(documentSpaceService.findHaveChildrenNode(space).size()!=0){
            result.setCode(40002);
            result.setMessage("该空间下存在子空间，不允许删除!!!");
            return result;
        }


        documentSpaceService.deleteSpaceById(space,account);


        return result;
    }


}
